/**
 * @Created by weicq weicq@yusys.com.cn on 2021-6-24 11:05:16.
 * @updated by
 * @description 营销活动管理
 */
define(['./libs/js-xlsx/xlsx.full.min.js',
        './custom/widgets/js/yufpOrgTree.js',
        './custom/plugins/YufpMgrSelector.js',
        './libs/moment/moment.js',
        './custom/widgets/js/yufpExtTree.js'],
    function (require, exports) {
        /**
         * 页面加载完成时触发
         * @param hashCode 路由ID
         * @param data 传递数据对象
         * @param cite 页面站点信息
         */
        exports.ready = function (hashCode, data, cite) {
            yufp.lookup.reg('ACT_TYPE,ACT_STATUS,ACT_SOURCE');
            yufp.custom.vue({
                    el: cite.el,
                    data: function () {
                        return {

                            //
                            // // 导出查询进度事件间隔
                            delay: 2000,
                            // 导出进度查询定时器
                            progressTimer: false,
                            progressUrl: '/api/NetworkLiabilityStatementsResource/queryDownloadInfo',
                            GridCustomerAUMAndProductCompositionReportData:{condition: JSON.stringify({
                                    // marketName: vm.$refs.actInfoSearch.formdata.marketName,
                                    // actSource: vm.$refs.actInfoSearch.formdata.actSource,
                                    // issusOrg: vm.$refs.actInfoSearch.formdata.issusOrg,
                                    userId: yufp.session.userId,
                                    orgId: yufp.session.user.org.code,
                                    roleId:yufp.session.user.roles[0].code,
                                })},
                            funcDataUrl:backend.msmFrontWebService + '/api/GridCustomerAUMAndProductCompositionReportResource/getGridCustomerAUMAndProductCompositionReportInfo',
                            loading: false,



                            dataUrl: '/api/wcrmMarketActivity/queryTableData',
                            treeUrlRel: backend.appOcaService + '/api/util/getorg',
                            formdata: {},
                            dialogVisible: false,
                            formDisabled: false,
                            viewType: 'DETAIL',
                            issusButton: !yufp.session.checkCtrl('issusButtonEdit'),
                            zsgxButton: !yufp.session.checkCtrl('zsgxEdit'),
                            zhxfButton1: !yufp.session.checkCtrl('zhxfEdit1'),
                            zhxfButton2: !yufp.session.checkCtrl('zhxfEdit2'),
                            roleLevel: '',
                            viewTitle: yufp.lookup.find('CRUD_TYPE', false),
                            options1:[],
                            saveBtnShow: true,
                            actInfoParams: {},
                            mgrFPVisible:false,
                            mgrFPFormdata:{},
                            mgrFPFormdataObject:{},
                            issusVisible: false,
                            issusFormdata: {},
                            issusVisibleForm: {},
                            actLeaderNameShow: false,
                            actCustNumShow: false,
                            loadingE: false,
                            actLeaderNameShow: false,
                            actCustNumShow: false,
                            marketNameDisable: false,
                            actSponsorDisable: false,
                            actPartnerDisable: false,
                            actStartTimeDisable: false,
                            actEndTimeDisable: false,
                            actTypeDisable: false,
                            actLeaderNameDisable: false,
                            actLeaderN: '',
                            actLeaderName: '',
                            actStatusShow: false,
                            upActShow: false,
                            actAddressShow: false,
                            params: {needCheckbox: true},
                            loadingB: false,
                            rules: {
                                marketName: [
                                    {required: true, message: '必填项', trigger: 'blur'}
                                ],
                                actSponsor: [
                                    {required: true, message: '必填项', trigger: 'blur'}
                                ],
                                actPartner: [
                                    {required: true, message: '必填项', trigger: 'blur'}
                                ],
                                // actStartTime: [
                                //   {required: true, message: '必填项', trigger: 'blur'}
                                // ],
                                // actEndTime: [
                                //   {required: true, message: '必填项', trigger: 'blur'}
                                // ],
                                actType: [
                                    {required: true, message: '必填项', trigger: 'blur'}
                                ],
                                actCustNum: [
                                    {required: true, message: '必填项', trigger: 'blur'}
                                ],
                                actAddress: [
                                    {required: true, message: '必填项', trigger: 'blur'}
                                ],
                                actLeaderName: [
                                    {required: true, message: '必填项', trigger: 'blur'}
                                ],
                                // latitude: [
                                //   {required: true, message: '必填项', trigger: 'blur'}
                                // ],
                                // sectionid: [
                                //   {required: true, message: '必填项', trigger: 'blur'}
                                // ]
                            },
                        };
                    },
                    mounted() {
                        this.getGridName()
                    },
                    created() {
                        var _this = this;
                        _this.initData();
                        _this.actInfoParams.condition = JSON.stringify({
                            orgId: yufp.session.user.org.code,
                            userId: yufp.session.userId,
                            roleLevel: _this.roleLevel,
                            roleId:yufp.session.user.roles[0].code,
                        });
                    },
                    methods: {
                        getGridName:function (){
                            var me =this;
                            yufp.service.request({
                                url: backend.msmFrontWebService + '/api/CustCenter/getOrgName',
                                method: 'get',
                                data: {
                                    condition: JSON.stringify({
                                        userId: yufp.session.userId,
                                        orgId: yufp.session.user.org.code,
                                        roleId:yufp.session.user.roles[0].code,
                                    })
                                },
                                callback: function (code, message, response) {
                                    me.options1 = response.data
                                }
                            });
                        },
                        exportExcel: function () {
                            var me = this;
                            me.loading = true;
                            yufp.service.request({
                                url: backend.msmFrontWebService + '/api/wcrmMarketActivity/exportExcel',
                                method: 'GET',
                                data: me.GridCustomerAUMAndProductCompositionReportData,
                                callback: function (code, message, res) {
                                    if (code != 0) {
                                        me.$message.error(message);
                                        return;
                                    }
                                    var taskId = res ? res.data : false;
                                    if (taskId) {
                                        me.taskId = taskId;
                                        me.progressVisible = true;
                                        me.progressTimer = setTimeout(me.showProgressFn(), me.delay);
                                    } else {
                                        me.$message.error('导出失败！');
                                    }
                                }
                            });
                        },
                        /**
                         * 轮询查询进度
                         * @param {String} taskId 任务ID
                         */
                        showProgressFn: function () {
                            var vm = this;
                            yufp.service.request({
                                url: vm.progressUrl,
                                method: 'GET',
                                data: {
                                    taskId: vm.taskId
                                },
                                callback: function (code, message, res) {
                                    window.console.info('-----res-----');
                                    window.console.info(res.data.percent);
                                    if (code != 0) {
                                        vm.$message.error(message);
                                        return;
                                    }
                                    vm.percentage = res.data.percent;
                                    if (res.data.percent < 100) {
                                        vm.progressTimer = setTimeout(vm.showProgressFn, vm.delay);
                                    } else {
                                        vm.downloadFile();
                                    }
                                }
                            });
                        },
                        downloadFile: function () {
                            var url = "";
                            url += yufp.settings.url;
                            url += '/' + backend.msmFrontWebService;
                            url += 'api/NetworkLiabilityStatementsResource/downloadDepExcel?' + 'taskId=' + this.taskId;
                            window.open(yufp.util.addTokenInfo(url));
                            this.loading = false;
                            this.exportVisible = false;
                            this.progressVisible = false;
                        },
                        chooseExecUser: function (data) {
                            var _this = this;
                            _this.initData();
                            _this.actLeaderN = '';
                            _this.actLeaderName = '';
                            _this.actLeaderN = data[0].orgName;
                            _this.actLeaderName = data[0].orgId;
                            console.info(_this.actLeaderN);
                            console.info(_this.actLeaderName);
                        },
                        initData: function () {
                            /*
                                根据不同角色等级查看不同的网格展示
                                总行->1级->
                                分行->2级->无此权限
                                支行->3级->
                                行长->4级->
                                客户经理->
                            */
                            console.info(yufp.session.roles[0].code)
                            if (yufp.session.roles[0].code == 'R0008' || yufp.session.roles[0].code == 'R0007' || yufp.session.roles[0].code == 'R001') {
                                this.roleLevel = '1';
                            } else if (yufp.session.roles[0].code == 'R0006') {

                            } else if (yufp.session.roles[0].code == 'R0005' || yufp.session.roles[0].code == 'R0003' || yufp.session.roles[0].code == 'R0004') {
                                this.roleLevel = '2';
                                this.actLeaderNameShow = true;
                            } else {
                                this.roleLevel = '3';
                                this.actLeaderNameShow = true;
                                this.actLeaderNameDisable = false;
                                // console.info("yufp.session.userId");
                                // console.info(yufp.session.userId);
                                this.formdata.actLeaderName = yufp.session.userName;
                                this.actLeaderN = yufp.session.userName;
                                this.actLeaderName = yufp.session.userId;
                                this.actCustNumShow = true;
                                this.actAddressShow = true;
                            }
                        },
                        //时间格式化
                        dateFormat: function (row, column) {
                            var date = row[column.property];
                            if (date == undefined) {
                                return "";
                            }
                            return moment(date).format("YYYY-MM-DD");
                        },
                        dateTimeFormat: function (row, column) {
                            var date = row[column.property];
                            if (date == undefined) {
                                return "";
                            }
                            return moment(date).format("YYYY-MM-DD HH:mm:ss");
                        },
                        saveMgrFP: function () {
                            var _this = this;
                            _this.loadingE = true;
                            var model = {};
                            console.info( this.mgrFPFormdata);
                            yufp.clone(_this.mgrFPFormdata, model);
                            yufp.service.request({
                                method: 'get',
                                url: backend.msmFrontWebService + '/api/wcrmMarketActivity/saveIssusMgr',
                                data: {
                                    condition: JSON.stringify({
                                        id: this.mgrFPFormdataObject.id,
                                        actId: this.mgrFPFormdataObject.actId,
                                        userID: this.mgrFPFormdata.userID,
                                        createOrg: yufp.session.user.org.code,
                                        userName: yufp.session.userName

                                    })
                                },
                                callback: function (code, message, response) {
                                    if (code == 0 && response.code == 0) {
                                        console.info(response.data);
                                        _this.$refs.refTable.remoteData(_this.actInfoParams);
                                        _this.mgrFPFormdata = {};
                                        _this.mgrFPFormdata.userID = "";
                                        _this.mgrFPVisible = false;
                                        _this.loadingE = false;
                                        _this.$message('操作成功');
                                    } else {
                                        console.info("失败");
                                    }
                                    _this.loading = false;
                                }
                            });
                        },


                        saveIssus: function () {
                            var _this = this;
                            _this.loading = true;
                            console.info(this.issusFormdata.execTopyNum)
                            //请求后台，过滤出叶子结点的ids
                            //进行数据处理（数据库生成多行下发代码，包括状态，id等）
                            yufp.service.request({
                                url: backend.msmFrontWebService + '/api/wcrmMarketActivity/saveIssus',
                                method: 'get',
                                // data: JSON.stringify(array),
                                data: {
                                    condition: JSON.stringify({
                                        execTopyNum: this.issusFormdata.execTopyNum,
                                        execTopyName: this.issusFormdata.execTopyName,
                                        createOrg: yufp.session.user.org.code,
                                        userName: yufp.session.userName,
                                        id: this.issusFormdata.id,
                                        actId: this.issusFormdata.actId
                                    })
                                },
                                callback: function (code, message, response) {
                                    if (code == 0 && response.code == 0) {
                                        console.info(response.data);
                                        _this.$refs.refTable.remoteData(_this.actInfoParams);
                                        _this.$message('操作成功');
                                    } else {
                                        console.info("失败");
                                    }
                                    _this.loading = false;
                                }
                            });
                            // this.$refs.execTopyNum1.clearSelect;
                            // console.info(this.$refs.execTopyNum1);
                            // console.info(this.$refs);
                            // console.info(this.$refs.execTopyNum1.$refs.execTopyNum1);
                            this.$refs.execTopyNum1.$refs.execTopyNum1.onIconClickFn();
                            this.issusFormdata.execTopyName = '';
                            this.issusFormdata.execTopyNum = '';
                            _this.issusVisible = false;

                        },
                        cancelIssusFn: function () {
                            var _this = this;
                            _this.issusVisible = false;
                            _this.loading = false;
                        },
                        setOrgName: function (data) {
                            console.log(data);
                            var result = false;
                            var orgId = '';
                            var orgName = '';
                            for (var i = 0; i < data.length; i++) {
                                console.log(data[i]);
                                // console.log(parseInt(this.addTaskData.execTopyType) + 2);
                                // if(data[i].orgLevel != parseInt(this.addTaskData.execTopyType) + 2){
                                //     this.$message({ message: '执行对象与执行对象类型不对应，请重新选择', type: 'warning' });
                                //     result = false;
                                //     break;
                                // }
                                if (i == 0) {
                                    orgId += data[i].orgId;
                                    orgName += data[i].orgName;
                                } else {
                                    orgId += ',' + data[i].orgId;
                                    orgName += ',' + data[i].orgName;
                                }
                                result = true;
                            }
                            console.log(result);
                            this.issusFormdata.execTopyNum = result ? orgId : '';
                            // console.log(this.$refs);
                            this.issusFormdata.execTopyName = result ? orgName : '';
                        },
                        searchFn: function () {
                            var vm = this;
                            var param = {
                                condition: JSON.stringify({
                                    marketName: vm.$refs.actInfoSearch.formdata.marketName,
                                    actSource: vm.$refs.actInfoSearch.formdata.actSource,
                                    issusOrg: vm.$refs.actInfoSearch.formdata.issusOrg,
                                    actType: vm.$refs.actInfoSearch.formdata.actType,
                                    actStatus: vm.$refs.actInfoSearch.formdata.actStatus,
                                    actStartTime: vm.$refs.actInfoSearch.formdata.actStartTime,
                                    actEndTime: vm.$refs.actInfoSearch.formdata.actEndTime
                                })
                            };
                            this.$refs.refTable.remoteData(param);
                        },
                        /**
                         * 取消
                         */
                        cancelFn: function () {
                            var _this = this;
                            _this.dialogVisible = false;
                            _this.loadingB = false;
                        },
                        /**
                         * 保存
                         */
                        saveFn: function () {
                            var _this = this;
                            _this.loadingB = true;
                            var model = {};
                            yufp.clone(_this.formdata, model);
                            console.info(_this.formdata);
                            console.info(model);
                            model.userName = yufp.session.userName;
                            model.roleLevel = _this.roleLevel;
                            if (_this.roleLevel == '1') {
                                model.actLeaderName = '';
                                model.actLeaderN = '';
                            } else if (_this.roleLevel == '2') {
                                model.actLeaderN = _this.actLeaderN;
                                model.actLeaderName = _this.actLeaderName;
                            } else {
                                model.actLeaderN = _this.actLeaderN;
                                model.actLeaderName = _this.actLeaderName;
                            }
                            model.createOrg = yufp.session.user.org.code;
                            model.orgId = yufp.session.user.org.code;
                            model.userId=yufp.session.userId;
                                model.roleId=yufp.session.user.roles[0].code;

                            if (model.roleId == "R0001"  || model.roleId == "R0002"  || model.roleId ==  "R0009" ) {
                                _this.$message('客户经理暂无权限');
                                return;
                            }
                                model.actStartTime = moment(model.actStartTime).format("YYYY-MM-DD");
                            model.actEndTime = moment(model.actEndTime).format("YYYY-MM-DD");
                            var validate = false;
                            _this.$refs.refForm.validate(function (valid) {
                                validate = valid;
                            });
                            if (!validate) {
                                return;
                            }
                            // 向后台发送保存请求
                            yufp.service.request({
                                method: 'POST',
                                url: '/api/wcrmMarketActivity/saveMarketActivity',
                                data: model,
                                callback: function (code, message, response) {
                                    _this.$refs.refTable.remoteData(_this.actInfoParams);
                                    _this.dialogVisible = false;
                                    _this.loadingB = false;
                                }
                            });
                        },
                        /**
                         * 控制保存按钮、xdialog、表单的状态
                         * @param viewType 表单类型
                         * @param editable 可编辑,默认false
                         */
                        switchStatus: function (viewType, editable) {
                            var _this = this;
                            _this.viewType = viewType;
                            _this.saveBtnShow = editable;
                            _this.dialogVisible = true;
                            _this.formDisabled = !editable;
                        },
                        /**
                         * 新增按钮
                         */
                        addFn: function () {
                            var _this = this;
                            let roleId = yufp.session.user.roles[0].code;
                            if (roleId== "R0001"  || roleId== "R0002"  || roleId ==  "R0009" ) {
                                _this.$message('客户经理暂无权限');
                                return;
                            }
                            _this.initData();
                            _this.switchStatus('ADD', true);
                            _this.$nextTick(function () {
                                _this.$refs.refForm.resetFields();
                            });

                        },
                        /**
                         * 修改
                         */
                        modifyFn: function () {
                            var _this = this;
                            let roleId = yufp.session.user.roles[0].code;
                            if ( roleId == "R0001"  ||  roleId == "R0002"  ||  roleId ==  "R0009" ) {
                                _this.$message('暂无权限修改支行下发活动');
                                return;
                            }
                            var selections = _this.$refs.refTable.selections;

                            if (roleId == "R0006"  || roleId  == "R0005"  || roleId   == "R0003"   || roleId   == "R0004" ) {
                                if(selections[0].createUser !=  yufp.session.userId) {
                                    _this.$message('非本人创建活动暂无权限修改');
                                    return;
                                }
                            }
                            _this.formdata.actLeaderName = '';
                            if (_this.$refs.refTable.selections.length != 1) {
                                _this.$message({message: '请先选择一条记录', type: 'warning'});
                                return;
                            }
                            console.info(_this.$refs.refTable.selections[0].actStatus)
                            console.info(_this.$refs.refTable.selections[0].actStatus != 1)
                            if (_this.$refs.refTable.selections[0].actStatus != "暂存") {
                                _this.$message({message: '只能修改暂存状态的活动', type: 'warning'});
                                return;
                            }
                            if (_this.$refs.refTable.selections[0].actLeader != yufp.session.userId && _this.roleLevel == '3') {//负责人可修改 机构所有人都能看
                                _this.$message({message: '只有负责人是自己的活动才能修改', type: 'warning'});
                                return;
                            }

                            if (_this.$refs.refTable.selections[0].createUser != yufp.session.userId && _this.roleLevel == '3') {
                                _this.marketNameDisable = true;
                                _this.actSponsorDisable = true;
                                _this.actPartnerDisable = true;
                                _this.actStartTimeDisable = true;
                                _this.actEndTimeDisable = true;
                                _this.actTypeDisable = true;
                                _this.actLeaderNameDisable = true;

                            }
                            if (_this.$refs.refTable.selections[0].createUser != yufp.session.userId && _this.roleLevel == '2') {
                                _this.marketNameDisable = true;
                                _this.actSponsorDisable = true;
                                _this.actPartnerDisable = true;
                                _this.actStartTimeDisable = true;
                                _this.actEndTimeDisable = true;
                                _this.actTypeDisable = true;
                            }
                            console.info(_this.$refs.refTable.selections[0])
                            _this.formdata.actLeaderName = _this.$refs.refTable.selections[0].actLeaderName;
                            _this.switchStatus('EDIT', true);
                            _this.$nextTick(function () {
                                _this.$refs.refForm.resetFields();
                                var obj = _this.$refs.refTable.selections[0];
                                yufp.clone(obj, _this.formdata);
                            });
                            _this.formdata.actLeaderName = _this.$refs.refTable.selections[0].actLeaderName;
                        },
                        /**
                         * 详情
                         */
                        infoFn: function () {
                            var _this = this;
                            var selectionsAry = _this.$refs.refTable.selections;
                            if (selectionsAry.length != 1) {
                                _this.$message({message: '请先选择一条记录', type: 'warning'});
                                return;
                            }
                            _this.switchStatus('DETAIL', false);
                            _this.$nextTick(function () {
                                _this.$refs.refForm.resetFields();
                                yufp.clone(selectionsAry[0], this.formdata);
                            });
                        },
                        /**
                         * 删除
                         */
                        deleteFn: function () {
                            var _this = this;
                            let roleId = yufp.session.user.roles[0].code;
                            if ( roleId === "R0001"  ||  roleId === "R0002"  ||  roleId ===  "R0009" ) {
                                _this.$message('暂无权限删除支行下发活动');
                                return;
                            }
                            var selections = _this.$refs.refTable.selections;
                            if (roleId === "R0006"  || roleId  === "R0005"  || roleId   === "R0003"   || roleId   === "R0004" ) {
                                if(selections[0].createUser !=  yufp.session.userId) {
                                    _this.$message('非本人创建活动暂无权限删除');
                                    return;
                                }
                            }

                            if (selections.length < 1) {
                                _this.$message({message: '请先选择一条记录', type: 'warning'});
                                return;
                            }
                            if (selections[0].actStatus != 1 && selections[0].actStatus !='暂存') {
                                _this.$message({message: '只能删除暂存状态的活动', type: 'warning'});
                                return;
                            }
                            var len = selections.length, arr = [];
                            for (var i = 0; i < len; i++) {
                                arr.push(selections[i].actId);
                            }
                            _this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                                type: 'warning',
                                callback: function (action) {
                                    if (action === 'confirm') {
                                        yufp.service.request({
                                            method: 'delete',
                                            url: '/api/wcrmMarketActivity/delete?ids=' + arr.join(','),
                                            data: {
                                                ids: arr.join(',')
                                            },
                                            callback: function (code, message, response) {
                                                _this.$refs.refTable.remoteData();
                                                _this.$message('操作成功');
                                            }
                                        });
                                    }
                                }
                            });
                        },
                        mgrFPVFn: function () {
                            var _this = this;
                            let roleId = yufp.session.user.roles[0].code;
                            if (roleId !== "R0006"  && roleId  !== "R0005"  && roleId   !== "R0003"  && roleId   !== "R0004" ) {
                                    _this.$message('非支行行长不能创建发布支行下发活动');
                                    return;
                            }
                            var selections = _this.$refs.refTable.selections;
                            if (selections.length != 1) {
                                _this.$message({message: '请选择一条记录进行下发', type: 'warning'});
                                return;
                            }
                            if (selections[0].actStatus == 2) {
                                _this.$message({message: '已下发的活动不能再次下发', type: 'warning'});
                                return;
                            }
                            // if (_this.roleLevel == '2') {
                            //     _this.$message({message: '行长不能下发营销活动', type: 'warning'});
                            //     return;
                            // }
                            console.info(selections);
                            _this.mgrFPFormdataObject.id = selections[0].id;
                            _this.mgrFPFormdataObject.actId = selections[0].actId;
                            _this.mgrFPVisible = true;
                            console.info(_this.mgrFPFormdataObject);
                            console.info(_this.mgrFPFormdataObject.id);
                            // yufp.service.request({
                            //     method: 'POST',
                            //     url: '/api/wcrmMarketActivity/issusMarketActivity',
                            //     data: model,
                            //     callback: function (code, message, response) {
                            //         _this.$refs.refTable.remoteData();
                            //         _this.$message('操作成功');
                            //         _this.dialogVisible = false;
                            //     }
                            // });
                        },
                        cancelMgrFn: function () {
                            this.mgrFPVisible = false;
                        },
                        /**
                         * 下发操作
                         */
                        issusFn: function () {
                            var _this = this;
                            let roleId = yufp.session.user.roles[0].code;
                            if ( roleId !== "R0008"  && roleId !==  "R0007"  &&  roleId !==  "R001" ) {
                                _this.$message({message: '非总行角色不能发布总行下发活动', type: 'warning'});
                                return;
                            }
                            var selections = _this.$refs.refTable.selections;
                            if (selections.length != 1) {
                                _this.$message({message: '请选择一条记录进行下发', type: 'warning'});
                                return;
                            }
                            if (selections[0].actStatus == 2) {
                                _this.$message({message: '已下发的活动不能再次下发', type: 'warning'});
                                return;
                            }
                            if (_this.roleLevel == '2') {
                                _this.$message({message: '行长不能下发营销活动', type: 'warning'});
                                return;
                            }
                            console.info(selections);
                            _this.issusFormdata.id = selections[0].id;
                            _this.issusFormdata.actId = selections[0].actId;
                            _this.issusVisible = true;
                            console.info(_this.issusFormdata);

                            // yufp.service.request({
                            //     method: 'POST',
                            //     url: '/api/wcrmMarketActivity/issusMarketActivity',
                            //     data: model,
                            //     callback: function (code, message, response) {
                            //         _this.$refs.refTable.remoteData();
                            //         _this.$message('操作成功');
                            //         _this.dialogVisible = false;
                            //     }
                            // });
                        }
                    }
                }
            );
        }
        ;
    })
;
